<?php

namespace App\Http\Requests;

use App\User;
use function foo\func;
use Illuminate\Foundation\Http\FormRequest;

class UserRequest extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return true;
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        return [
            'name'=>'required|unique:users',
            'password'=>'min:6|required|confirmed',
            'account'=>[
                'required',
                function($attribute, $value, $fail) {
                    //走到此处验证是邮箱  此处value是 account的值 验证失败$fail 接收失败信息
                    if(filter_var($value,FILTER_VALIDATE_EMAIL)){
                        $user = User::where('email',$value)->first();
                        if($user){
                            return $fail('邮箱已经注册，请更换');
                        }
                        return true;
                    }else{
                        //走到此处是手机
                        $user = User::where('phone',$value)->first();

                        if ($user){
                            return $fail('手机号已经存在,请更换');
                        }
                        return true;
                    }
                }
            ],
            'code'=>[
                'required',
                function($attribute, $value, $fail) {
                    if($value != session('valid_code.code')){
                        return $fail('验证码错误');
                    }
                    return true;
                }
            ]
        ];
    }

    //错误消息
    public  function messages()
    {
        return[
            'name.required'=>'昵称不能为空',
            'name.unique'=>'昵称已存在',
            'password.min'=>'密码不能少于6位',
            'password.confirmed'=>'两次密码输入不一致',
            'password.required'=>'输入的密码不能为空',
            'account.required'=>'您的账号不能为空',
            'code.required'=>'您的验证码不能为空'

        ];
    }

}
